#include "mode_preservation.h"
#include "actuator_control.h"
#include "sensors.h"
#include <stdio.h>

// 保鲜模式状态
static struct {
    uint32_t last_check_time;          // 上一次温度检查的时间（秒级），用于定时检查温度
    bool compressor_state;             // 当前压缩机状态（开/关）
    bool compressor_started;           // 压缩机是否已经启动
    uint32_t compressor_delay_end;     // 压缩机延迟启动的时间点（毫秒）
    const SystemConfig *config;        // 指向系统配置的指针，保存保鲜模式的配置参数
} preservation_state;

// 初始化保鲜模式
void mode_preservation_init(const SystemConfig *config) {
    if (config) {
        preservation_state.config = config;
    }
    // 初始化状态变量
    preservation_state.last_check_time = 0;
    preservation_state.compressor_state = false;
    preservation_state.compressor_started = false;
    preservation_state.compressor_delay_end = 0;
}

// 进入保鲜模式
void mode_preservation_enter(void) {
    printf("Entering preservation mode\n");
    
    // 初始化时间和状态
    preservation_state.last_check_time = get_system_time_sec();
    preservation_state.compressor_state = true;
    preservation_state.compressor_started = false;
    preservation_state.compressor_delay_end = get_system_time_ms() + preservation_state.config->compressor_on_delay*1000;  // 8秒延迟
    
    // 立即开启主电机和预冷缸制冷阀
    actuator_set_main_motor(true);
    actuator_set_precool_valve(true);
}

// 退出保鲜模式
void mode_preservation_exit(void) {
    printf("Exiting preservation mode\n");
    
    // 关闭相关设备
    actuator_set_main_motor(false);
    actuator_set_precool_valve(false);
    actuator_set_compressor(false);
}

// 处理保鲜模式逻辑
ModeStatus mode_preservation_process(void) {
    uint32_t current_time_ms = get_system_time_ms();
    uint32_t current_time_sec = get_system_time_sec();
    int current_temp = sensor_get_temperature();
    
    // 定时检查温度 (每隔设定的间隔)
    if (current_time_sec - preservation_state.last_check_time >= preservation_state.config->check_interval) {
        preservation_state.last_check_time = current_time_sec;
        printf("Preservation temperature check: %d°C\n", current_temp);
        
        // 检查温度是否在目标范围内
        int lower_bound = preservation_state.config->preservation_temp - 
                           preservation_state.config->preservation_hysteresis;
        int upper_bound = preservation_state.config->preservation_temp + 
                           preservation_state.config->preservation_hysteresis;
        
        if (current_temp < lower_bound) {
            // 温度过低，关闭压缩机
            if (preservation_state.compressor_state) {
                actuator_set_compressor(false);
                preservation_state.compressor_state = false;
                preservation_state.compressor_started = false;
                printf("Temperature below threshold, turning off compressor\n");
            }
        } 
        else if (current_temp > upper_bound) {
            // 温度过高，开启压缩机
            if (!preservation_state.compressor_state) {
                preservation_state.compressor_state = true;
                preservation_state.compressor_started = false;
                preservation_state.compressor_delay_end = current_time_ms +  preservation_state.config->compressor_on_delay*1000;  // 8秒延迟
                printf("Temperature above threshold, preparing to turn on compressor\n");
            }
        }
        else if (current_temp <= preservation_state.config->preservation_temp) {
            // 达到目标温度，停止保鲜模式
            printf("Temperature reached target (%d°C), stopping preservation\n", current_temp);
            return MODE_STATUS_COMPLETE;
        }
    }
    
    // 处理压缩机延迟启动
    if (preservation_state.compressor_state && !preservation_state.compressor_started && 
        current_time_ms >= preservation_state.compressor_delay_end) {
        actuator_set_compressor(true);
        preservation_state.compressor_started = true;
        printf("Compressor started after 8s delay\n");
    }
    
    return MODE_STATUS_RUNNING;  // 继续运行
}
    